var move = false;
var countNewRow = 0;


$(document).ready(function(){
	$('a[rel=edit]').live('click',function(clickEvent) {
		clickEvent.preventDefault();
		$(this).closest('tr').load($(this).attr('href'));
	});
	
	$('a[rel=save]').live('click', function(clickEvent){
		clickEvent.preventDefault();
		var DOM_Element = $(this).closest('tr');
		DOM_Element.load($(this).attr('href'), $("#" + DOM_Element.attr('id') + " :input").serializeArray(), 
			function(result) {
				if($('#content-location-left-tree').length) {
					$('#content-location-left-tree').load(__HOST_NAME__ + '/' + controller + "/locTree");
				}
				return;
			}
		);
	});
	
	$('a[rel=cancel]').live('click', function(clickEvent) {
		clickEvent.preventDefault();
		$(this).closest('tr').remove();
	});
	
	$('a[rel=add]').live('click', function(clickEvent) {
		clickEvent.preventDefault();
		table_row = '<tr id="newRow' + countNewRow + '" class="newRowAdd"></tr>';
		//$(".pages-table tr:first").after(table_row);
		$(this).closest('div').find('.normal').find('tr:first').after(table_row);
		$(table_row).insertBefore('tr.bulkActions');
		$('#newRow' + countNewRow).load($(this).attr('href'));
		countNewRow++;
	});
	
	$('a[rel=delete]').live('click',function(clickEvent) {
		clickEvent.preventDefault();
		DOM_Element = $(this);
		if (!confirm('Please confirm. It cannot be undone.')) {
			return;
		}
		$.post($(this).attr('href'), function(result) {
			if(result.substr(0, 7) == 'Success') {
				DOM_Element.closest('tr').remove();
				if($('#content-location-left-tree').length) {
					$('#content-location-left-tree').load(__HOST_NAME__ + '/' + controller + "/locTree");
				}
			} else {
				alert('Could not delete the record. Please try again.')
			}
			return;
		});
	});

	$('p.tree').live('click', function() {
		link = 'add';
		DOM_element = $(this);
		parentId = DOM_element.attr('id');
		path = controller + '/treeUpdate';
		$('#tabs-1').html('Loading.......');
		$('#tabs-1').load(__HOST_NAME__ + '/' + path, {
			name: parentId
		}, function(result) {
			$('#addnew').attr('href', __HOST_NAME__ + '/' + controller + '/' + link + '/' + parentId);
			return;
		});
	});
});

function updateIndexParentId(parentId) {
	$('#tabs-1').html('<img class="loading" src="' + __HOST_NAME__ + '/img/loading.gif" />');
	$('#tabs-1').load(__HOST_NAME__ + controller + '/treeUpdate',{
		name: parentId
	}, function(result) {
		$('#addnew').attr('href', __HOST_NAME__ + '/' + controller + '/add/' + parentId);
		return;
	});
}